import tkinter as tk
from tkinter import ttk, Text
from tkinter import messagebox
from datetime import datetime
from tkcalendar import DateEntry
import pandas as pd
from setting import Setting



class Rental:
    def __init__(self):
        self.setting = Setting()
        self.url_fileRentalInfo = self.setting.url_fileRentalInfo
        self.url_fileTenantInfo = self.setting.url_fileTenantInfo
        # 获取水电单价
        self.warterPrice = self.setting.get_warterPrice()
        self.electricPrice = self.setting.get_electricPrice()

    def frame3RentalShow(self):  # 在租客信息页展示租客信息，可重复调用，调用后会进行覆盖
        df = pd.read_excel(self.url_fileRentalInfo, sheet_name='Rental', engine='openpyxl', header=0)
        # 取得数据后按期间和房间排序
        df = df.sort_values(by=[df.columns[0], df.columns[1]], ascending=[False, True])
        line = len(df)
        # 清空数据
        self.canvas2.delete(*self.canvas2.get_children())
        for i in range(line):
            self.canvas2.insert("", "end", values=(df.iloc[i, 0], df.iloc[i, 1], df.iloc[i, 2], df.iloc[i, 3], df.iloc[i, 4],
                                                   df.iloc[i, 5], df.iloc[i, 6], df.iloc[i, 7], df.iloc[i, 8], df.iloc[i, 9],
                                                   df.iloc[i, 10], df.iloc[i, 11], df.iloc[i, 12], df.iloc[i, 13]))


    def rentalManger(self, frame3):  # 收租管理

        """设置布局"""
        canvas1 = tk.Canvas(frame3, width=500, height=200)
        canvas1.pack(side=tk.TOP)
        canvas = tk.Canvas(frame3, width=500, height=10, bg="blue")  # , bg="blue"
        canvas.pack()
        canvas3 = tk.Canvas(frame3, height=600)  # , bg="red", width=500, height=600
        canvas3.pack()  # side=tk.BOTTOM
        """设置查询管理"""
        LabelTitler = ttk.Label(canvas1, text="收租期间", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=0)
        #self.enTmonth = ttk.Entry(canvas1, width=12)
        #self.enTmonth.grid(row=1, column=0, sticky='nsew')
        self.enTmonth = ttk.Combobox(canvas1, width=9)
        self.enTmonth['values'] = self.setting.monthList()  # 赋值列表
        self.enTmonth.grid(row=1, column=0, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="房间号", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=1)
        #self.enTroomid = ttk.Entry(canvas1, width=12)
        #self.enTroomid.grid(row=1, column=1, sticky='nsew')
        self.enTroomid = ttk.Combobox(canvas1, width=9)
        self.enTroomid['values'] = self.setting.roomList(self.url_fileTenantInfo, 'Tenant')  # 赋值列表
        self.enTroomid.grid(row=1, column=1, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="租客姓名", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=2)
        self.enTtenant = ttk.Entry(canvas1, width=12)
        self.enTtenant.grid(row=1, column=2, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="收租日期", relief="solid", padding=(4, 4), width=12,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=3)
        self.enTrentaltime = DateEntry(canvas1, date_pattern='YYYY-MM-DD', width=12)
        self.enTrentaltime.grid(row=1, column=3, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="本月水表底1", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=4)
        self.enTwarter1 = ttk.Entry(canvas1, width=12)
        self.enTwarter1.grid(row=1, column=4, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="上月水表底1", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=5)
        self.enTwarter1last = ttk.Entry(canvas1, width=12)
        self.enTwarter1last.grid(row=1, column=5, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="本月水表底2", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=6)
        self.enTwarter2 = ttk.Entry(canvas1, width=12)
        self.enTwarter2.grid(row=1, column=6, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="上月水表底2", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=0, column=7)
        self.enTwarter2last = ttk.Entry(canvas1, width=12)
        self.enTwarter2last.grid(row=1, column=7, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="本月电表底1", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=2, column=4)
        self.enTelectric1 = ttk.Entry(canvas1, width=12)
        self.enTelectric1.grid(row=3, column=4, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="上月电表底1", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=2, column=5)
        self.enTelectric1last = ttk.Entry(canvas1, width=12)
        self.enTelectric1last.grid(row=3, column=5, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="本月电表底2", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=2, column=6)
        self.enTelectric2 = ttk.Entry(canvas1, width=12)
        self.enTelectric2.grid(row=3, column=6, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="上月电表底2", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=2, column=7)
        self.enTelectric2last = ttk.Entry(canvas1, width=12)
        self.enTelectric2last.grid(row=3, column=7, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="月租金", relief="solid", padding=(4, 4), width=10,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=2, column=2)
        self.enTamount = ttk.Entry(canvas1, width=12)
        self.enTamount.grid(row=3, column=2, sticky='nsew')
        LabelTitler = ttk.Label(canvas1, text="总租金(含水电)", relief="solid", padding=(4, 4), width=12,
                                font=("微软雅黑", 10, "bold"), anchor="center")
        LabelTitler.grid(row=2, column=3)
        self.enTamounttotal = ttk.Entry(canvas1, width=14)
        self.enTamounttotal.grid(row=3, column=3, sticky='nsew')

        hpBtn4 = ttk.Button(canvas1, text="查找", command=self.findRental)
        hpBtn4.grid(row=2, column=0, sticky='nsew')
        hpBtn4 = ttk.Button(canvas1, text="算租", command=self.calRental)
        hpBtn4.grid(row=2, column=1, sticky='nsew')
        hpBtn1 = ttk.Button(canvas1, text="添加", command=self.addRental)
        hpBtn1.grid(row=3, column=0, sticky='nsew')
        hpBtn2 = ttk.Button(canvas1, text="修改", command=self.modifyRental)
        hpBtn2.grid(row=3, column=1, sticky='nsew')
        hpBtn3 = ttk.Button(canvas1, text="删除", command=self.delRental)
        hpBtn3.grid(row=4, column=0, columnspan=2, sticky='nsew')
        # 设置表头
        self.canvas2 = ttk.Treeview(canvas3,
                                    columns=("month", "roomid", "name", "rentaltime", "warter1", "warter1last", "warter2", "warter2last",
                                             "electric1", "electric1last", "electric2", "electric2last", "amount", "amounttotal"), show="headings")
        self.canvas2['height'] = 20 #设置默认显示行数
        self.canvas2.heading("month", text="收租期间")
        self.canvas2.heading("roomid", text="房间号")
        self.canvas2.heading("name", text="租客姓名")
        self.canvas2.heading("rentaltime", text="收租日期")
        self.canvas2.heading("warter1", text="本月水表底1")
        self.canvas2.heading("warter1last", text="上月水表底1")
        self.canvas2.heading("warter2", text="本月水表底2")
        self.canvas2.heading("warter2last", text="上月水表底2")
        self.canvas2.heading("electric1", text="本月电表底1")
        self.canvas2.heading("electric1last", text="上月电表底1")
        self.canvas2.heading("electric2", text="本月电表底2")
        self.canvas2.heading("electric2last", text="上月电表底2")
        self.canvas2.heading("amount", text="月租金")
        self.canvas2.heading("amounttotal", text="总租金")
        # 设置列宽
        self.canvas2.column("month", width=60, anchor='center')
        self.canvas2.column("roomid", width=60, anchor='center')
        self.canvas2.column("name", width=70, anchor='center')
        self.canvas2.column("rentaltime", width=80)
        self.canvas2.column("warter1", width=80)
        self.canvas2.column("warter1last", width=80)
        self.canvas2.column("warter2", width=80, anchor='center')
        self.canvas2.column("warter2last", width=80, anchor='center')
        self.canvas2.column("electric1", width=80, anchor='center')
        self.canvas2.column("electric1last", width=80, anchor='center')
        self.canvas2.column("electric2", width=80, anchor='center')
        self.canvas2.column("electric2last", width=80, anchor='center')
        self.canvas2.column("amount", width=60, anchor='center')
        self.canvas2.column("amounttotal", width=60, anchor='center')
        self.canvas2.pack(side=tk.LEFT)

        scrollbar = tk.Scrollbar(canvas3, orient="vertical", command=self.canvas2.yview())
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.canvas2.configure(yscrollcommand=scrollbar.set)

        self.frame3RentalShow()

    def findRental(self):
        month = self.enTmonth.get()
        roomid = self.enTroomid.get()
        # 如果没有输入收盘期间或房间号则提示且退出
        if month == '' or roomid == '':
            messagebox.showwarning("提示", "请输入'收租期间'和'房间号'！")
            return
        # 获取水电单价
        #warterPrice = self.setting.get_warterPrice()
        #electricPrice = self.setting.get_electricPrice()
        df = pd.read_excel(self.url_fileRentalInfo, sheet_name='Rental', engine='openpyxl', header=0)
        # 构造时间+房间的查询条件
        f_month = df['month'] == int(month)
        f_roomid = df['roomid'] == roomid
        # 如果没有查到记录则提示且退出
        if len(df.index[f_month & f_roomid]) == 0:
            messagebox.showwarning("提示", "本月无收租记录！")
            return
        try:
            # 定义条件
            row_index = df.index[f_month & f_roomid].tolist()[0]  # 获取需要删除房间索引
            if month[4:6] == '01':
                monthLast = int(month) - 100 + 11
            else:
                monthLast = int(month) - 1
            f_monthLast = df['month'] == int(monthLast)
            if len(df.index[f_monthLast & f_roomid]) == 0:
                messagebox.showwarning("提示", "上月无收租记录！")
                row_indexLast = -1
            else:
                row_indexLast = df.index[f_monthLast & f_roomid].tolist()[0]  # 获取需要删除房间索引
        except Exception as e:
            messagebox.showwarning("提示", "本月无收租记录！")
            print(f"发生了一个错误：{e}")
        else:
            name = df.loc[row_index, 'name']
            rentaltime = df.loc[row_index, 'rentaltime']
            warter1 = df.loc[row_index, 'warter1']
            warter2 = df.loc[row_index, 'warter2']
            electric1 = df.loc[row_index, 'electric1']
            electric2 = df.loc[row_index, 'electric2']
            amount = df.loc[row_index, 'amount']
            if row_indexLast != -1:
                warter1last = df.loc[row_indexLast, 'warter1']
                warter2last = df.loc[row_indexLast, 'warter2']
                electric1last = df.loc[row_indexLast, 'electric1']
                electric2last = df.loc[row_indexLast, 'electric2']
            else:
                warter1last = 0
                warter2last = 0
                electric1last = 0
                electric2last = 0
            amounttotal = amount + (electric1 - electric1last) * self.electricPrice + (
                        electric2 - electric2last) * self.electricPrice \
                          + (warter1 - warter1last) * self.warterPrice + (warter2 - warter2last) * self.warterPrice
            self.setting.reloadENT(self.enTtenant, name)
            self.enTrentaltime.set_date(datetime.strptime(rentaltime, '%Y-%m-%d'))
            self.setting.reloadENT(self.enTwarter1, warter1)
            self.setting.reloadENT(self.enTwarter1last, warter1last)
            self.setting.reloadENT(self.enTwarter2, warter2)
            self.setting.reloadENT(self.enTwarter2last, warter2last)
            self.setting.reloadENT(self.enTelectric1, electric1)
            self.setting.reloadENT(self.enTelectric1last, electric1last)
            self.setting.reloadENT(self.enTelectric2, electric2)
            self.setting.reloadENT(self.enTelectric2last, electric2last)
            self.setting.reloadENT(self.enTamount, amount)
            self.setting.reloadENT(self.enTamounttotal, amounttotal)


    def addRental(self):
        month = self.enTmonth.get()
        roomid = self.enTroomid.get()
        # 如果没有输入收租期间或房间号则提示且退出
        if month == '' or roomid == '':
            messagebox.showwarning("提示", "请输入'收租期间'和'房间号'！")
            return
        # 获取水电单价
        #warterPrice = self.setting.get_warterPrice()
        #electricPrice = self.setting.get_electricPrice()
        df = pd.read_excel(self.url_fileRentalInfo, sheet_name='Rental', engine='openpyxl', header=0)
        # 构造时间+房间的查询条件
        f_month = df['month'] == int(month)
        f_roomid = df['roomid'] == roomid
        # 如果没有查到记录则提示且退出
        if len(df.index[f_month & f_roomid]) == 1:
            messagebox.showwarning("提示", "本月已有收租记录，请使用修改方式调整！")
        else:
            name = self.enTtenant.get()
            rentaltime = self.enTrentaltime.get()
            warter1 = self.enTwarter1.get()
            warter2 = self.enTwarter2.get()
            electric1 = self.enTelectric1.get()
            electric2 = self.enTelectric2.get()
            amount = self.enTamount.get()
            warter1last = self.enTwarter1last.get()
            warter2last = self.enTwarter2last.get()
            electric1last = self.enTelectric1last.get()
            electric2last = self.enTelectric2last.get()
            amounttotal   = float(amount) + (float(electric1) - float(electric1last)) * self.electricPrice + (float(electric2) - float(electric2last)) * self.electricPrice\
                            + (float(warter1) - float(warter1last)) * self.warterPrice + (float(warter2) - float(warter2last)) * self.warterPrice

            row_index = len(df)
            df.loc[row_index + 1, 'month']         = int(month)
            df.loc[row_index + 1, 'roomid']        = roomid
            df.loc[row_index + 1, 'name']          = name
            df.loc[row_index + 1, 'rentaltime']    = rentaltime
            df.loc[row_index + 1, 'warter1']       = float(warter1)
            df.loc[row_index + 1, 'warter2']       = float(warter2)
            df.loc[row_index + 1, 'electric1']     = float(electric1)
            df.loc[row_index + 1, 'electric2']     = float(electric2)
            df.loc[row_index + 1, 'amount']        = float(amount)
            df.loc[row_index + 1, 'amounttotal']   = float(amounttotal)
            df.loc[row_index + 1, 'warter1last']   = float(warter1last)
            df.loc[row_index + 1, 'warter2last']   = float(warter2last)
            df.loc[row_index + 1, 'electric1last'] = float(electric1last)
            df.loc[row_index + 1, 'electric2last'] = float(electric2last)
            df.loc[row_index + 1, 'createtime'] = datetime.now()
            df.loc[row_index + 1, 'lastupdatetime'] = datetime.now()
            # 将DataFrame对象写入特定的工作表和行
            df.to_excel(self.url_fileRentalInfo, index=False, header=True, sheet_name='Rental', startrow=0)
            self.frame3RentalShow() #重新展示租客户信息

    def modifyRental(self):
        month = self.enTmonth.get()
        roomid = self.enTroomid.get()
        # 如果没有输入收盘期间或房间号则提示且退出
        if month == '' or roomid == '':
            messagebox.showwarning("提示", "请输入'收租期间'和'房间号'！")
            return
        df = pd.read_excel(self.url_fileRentalInfo, sheet_name='Rental', engine='openpyxl', header=0)
        # 构造时间+房间的查询条件
        f_month = df['month'] == int(month)
        f_roomid = df['roomid'] == roomid
        # 如果没有查到记录则提示且退出
        if len(df.index[f_month & f_roomid]) == 0:
            messagebox.showwarning("提示", "本月无收租记录！")
            return
        try:
            # 定义条件
            row_index = df.index[f_month & f_roomid].tolist()[0]  # 获取需要修改记录的索引
        except Exception as e:
            messagebox.showwarning("提示", "本月无收租记录！")
            print(f"发生了一个错误：{e}")
        else:
            name = self.enTtenant.get()
            rentaltime = self.enTrentaltime.get()
            warter1 = self.enTwarter1.get()
            warter2 = self.enTwarter2.get()
            electric1 = self.enTelectric1.get()
            electric2 = self.enTelectric2.get()
            amount = self.enTamount.get()
            warter1last = self.enTwarter1last.get()
            warter2last = self.enTwarter2last.get()
            electric1last = self.enTelectric1last.get()
            electric2last = self.enTelectric2last.get()
            amounttotal = self.enTamounttotal.get()

            df.loc[row_index, 'month'] = int(month)
            df.loc[row_index, 'roomid'] = roomid
            df.loc[row_index, 'name'] = name
            df.loc[row_index, 'rentaltime'] = rentaltime
            df.loc[row_index, 'warter1'] = float(warter1)
            df.loc[row_index, 'warter2'] = float(warter2)
            df.loc[row_index, 'electric1'] = float(electric1)
            df.loc[row_index, 'electric2'] = float(electric2)
            df.loc[row_index, 'amount'] = float(amount)
            df.loc[row_index, 'amounttotal'] = float(amounttotal)
            df.loc[row_index, 'warter1last'] = float(warter1last)
            df.loc[row_index, 'warter2last'] = float(warter2last)
            df.loc[row_index, 'electric1last'] = float(electric1last)
            df.loc[row_index, 'electric2last'] = float(electric2last)
            #df.loc[row_index1, 'createtime'] = datetime.now()
            df.loc[row_index, 'lastupdatetime'] = datetime.now()
            # 将DataFrame对象写入特定的工作表和行
            df.to_excel(self.url_fileRentalInfo, index=False, header=True, sheet_name='Rental', startrow=0)
            messagebox.showwarning("提示", "修改成功！")
            self.frame3RentalShow()  # 重新展示租客户信息

    def delRental(self):
        month = self.enTmonth.get()
        roomid = self.enTroomid.get()
        # 如果没有输入收租期间或房间号则提示且退出
        if month == '' or roomid == '':
            messagebox.showwarning("提示", "请输入'收租期间'和'房间号'！")
            return
        df = pd.read_excel(self.url_fileRentalInfo, sheet_name='Rental', engine='openpyxl', header=0)
        # 构造时间+房间的查询条件
        f_month = df['month'] == int(month)
        f_roomid = df['roomid'] == roomid
        # 如果没有查到记录则提示且退出
        if len(df.index[f_month & f_roomid]) == 1:
            row_index = df.index[f_month & f_roomid]
            df = df.drop(row_index) #根据索引删除数据
            # 将DataFrame对象写入特定的工作表和行
            df.to_excel(self.url_fileRentalInfo, index=False, header=True, sheet_name='Rental', startrow=0)
            messagebox.showwarning("提示", "已删除成功！")
            self.frame3RentalShow() #重新展示租客户信息
        else:
            messagebox.showwarning("提示", "本月未有收租记录，请检查！")

    def calRental(self):
        warter1 = self.enTwarter1.get()
        warter2 = self.enTwarter2.get()
        electric1 = self.enTelectric1.get()
        electric2 = self.enTelectric2.get()
        amount = self.enTamount.get()
        warter1last = self.enTwarter1last.get()
        warter2last = self.enTwarter2last.get()
        electric1last = self.enTelectric1last.get()
        electric2last = self.enTelectric2last.get()
        amounttotal = float(amount) + (float(electric1) - float(electric1last)) * self.electricPrice + (float(electric2) - float(electric2last)) * self.electricPrice \
                      + (float(warter1) - float(warter1last)) * self.warterPrice + (float(warter2) - float(warter2last)) * self.warterPrice
        self.setting.reloadENT(self.enTamounttotal, amounttotal)
        messagebox.showwarning("提示", "计算完成！")

